# 管理员权限检查
#Requires -RunAsAdministrator

Write-Host "=== 开始配置 WSL Arch Linux ===" -ForegroundColor Cyan

# 启用 WSL 功能
Write-Host "`n1. 启用 WSL 和虚拟机平台功能..." -ForegroundColor Yellow
dism.exe /online /enable-feature /featurename:Microsoft-Hyper-V /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

# 下载 WSL2 内核更新包
Write-Host "`n2. 安装 WSL2 内核更新..." -ForegroundColor Yellow
$kernelInstaller = "$env:TEMP\wsl_update_x64.msi"
Invoke-WebRequest -Uri https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi -OutFile $kernelInstaller
Start-Process -FilePath $kernelInstaller -ArgumentList "/quiet" -Wait
Remove-Item $kernelInstaller -ErrorAction SilentlyContinue

# 设置 WSL2 为默认版本
wsl --set-default-version 2

# 下载 Arch WSL 发行版（使用第三方打包的 ArchWSL）
Write-Host "`n3. 下载 Arch Linux WSL 发行版..." -ForegroundColor Yellow
$archZip = "$env:TEMP\Arch.zip"
Invoke-WebRequest -Uri https://github.com/yuk7/ArchWSL/releases/latest/download/Arch.zip -OutFile $archZip

# 安装到指定目录
$installPath = "C:\WSL\Arch"
New-Item -ItemType Directory -Path $installPath -Force | Out-Null
Expand-Archive -Path $archZip -DestinationPath $installPath -Force
Remove-Item $archZip -ErrorAction SilentlyContinue

# 初始化 Arch 实例
Write-Host "`n4. 初始化 Arch 环境..." -ForegroundColor Yellow
Set-Location $installPath
.\Arch.exe install

# 设置为默认 WSL 发行版
wsl --set-default Arch

# 配置 Arch 基础环境
Write-Host "`n5. 配置 Arch 系统..." -ForegroundColor Yellow
wsl -u root << 'EOF'
# 设置镜像源（使用国内源）
echo 'Server = https://mirrors.ustc.edu.cn/archlinux/$repo/os/$arch' > /etc/pacman.d/mirrorlist
echo 'Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/$repo/os/$arch' >> /etc/pacman.d/mirrorlist

# 更新系统
pacman-key --init
pacman-key --populate archlinux
pacman -Syu --noconfirm

# 安装基础工具
pacman -S --noconfirm base-devel git zsh neovim wget curl

# 创建普通用户并赋予 sudo 权限
useradd -m -G wheel -s /bin/zsh archuser
echo "archuser ALL=(ALL) ALL" >> /etc/sudoers
echo "archuser:123456" | chpasswd  # 临时密码，首次登录需修改

# 配置默认登录用户
echo -e "[user]\ndefault = archuser" > /etc/wsl.conf
EOF

# 重启 WSL 使配置生效
wsl --shutdown
wsl --start

Write-Host "`n=== Arch Linux WSL 配置完成 ===" -ForegroundColor Green
Write-Host "使用命令 'wsl' 进入系统，首次登录用户: archuser 密码: 123456" -ForegroundColor Cyan
Write-Host "建议登录后立即使用 'passwd' 命令修改密码" -ForegroundColor Yellow
